﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AgeWizardPageView.xaml.cs" company="WildGums">
//   Copyright (c) 2008 - 2015 WildGums. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------


namespace Orc.Wizard.Example.Wizard.Views
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Windows;

    public partial class AgeWizardPageView
    {
        public AgeWizardPageView()
        {
            InitializeComponent();
            //  serviceip.ItemsSource = GetIP();
            // serviceip.SelectedValuePath = "oid";
            // serviceip.DisplayMemberPath = "name";
            // serviceip.SelectedIndex = 0;
            IPAddress[] ip = GetIP();
            foreach (var addip in ip)
            {

                 string add = addip.ToString();
                if (char.IsNumber(add, 0))
                {
                    serviceip.Items.Add(addip); 
                    
                }
               
            }
            
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string ip = this.serviceip.Text.Trim();
            string sqlname = "smop";//this.sqlname.Text.Trim();
            string sqluid = this.sqluid.Text.Trim();
            string password = this.passwrod.Text.Trim();

            var allsqlnames = GetAllDataBase(ip, sqluid, password);
            //还原数据库huagong
            if (!(allsqlnames.IndexOf("huagong") != -1))
            {
                Reduction(ip, sqluid, password, "huagong", "../huagong.bak");
            }
            //还原数据库huagong
            if (!(allsqlnames.IndexOf(sqlname) != -1))
            {
                Reduction(ip, sqluid, password, "smop", "../smop.bak");
            }
            //  FilePath contex = new FilePath();
            // contex.FIlepath = @"D:\wwwroot\smop\web.config";
            //  contex.Fileindexof = string.Format("<add name=\"Default\" connectionString=\"server = {0}; uid = {1}; pwd = {2};database={3};\" providerName=\"System.Data.SqlClient\" />", ip, sqluid, password, sqlname);
            // contex.newConString = "name =\"Default\"";

            if (string.IsNullOrEmpty(ip)|| string.IsNullOrEmpty(sqlname) || string.IsNullOrEmpty(sqluid) || string.IsNullOrEmpty(password) )
            {
                MessageBox.Show("不能为空");
            }
            else
            {
                for (int i = 1; i < 24; i++)
                {
                    FilePath path = GetPath(i, ip, sqlname, sqluid, password,"huagong");
                    SetFileAttributes(path.FIlepath);
                    ModifyFile(path.FIlepath, path.newConString, path.Fileindexof);
                }                             
                //  ModifyFile(contex.FIlepath, contex.newConString, contex.Fileindexof);
                MessageBox.Show("保存成功");
            }
        }

        private void Reduction(string ip, string uid, string password,string dbname,string filepath)
        {
            if(!File.Exists(filepath)) return;
            SqlConnection Connection = new SqlConnection(
             String.Format("Data Source={0};Initial Catalog=master;User ID={1};PWD={2}", ip, uid,
                password));
           
            string cmdStr = string.Format("use master restore database {0} from disk='{1}'", dbname, filepath);
            SqlCommand cmd = new SqlCommand(cmdStr, Connection);
            try
            {
                Connection.Open();
                cmd.CommandTimeout = 100;//解决问题二
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {                
            }
            finally
            {
                Connection.Close();
            }
        }

        private ArrayList GetAllDataBase(string ip,string uid,string password)
        {
            try
            {
                ArrayList DBNameList = new ArrayList();
                SqlConnection Connection = new SqlConnection(
                    String.Format("Data Source={0};Initial Catalog=master;User ID={1};PWD={2}", ip, uid,
                        password));
                DataTable DBNameTable = new DataTable();
                SqlDataAdapter Adapter = new SqlDataAdapter("select name from master..sysdatabases", Connection);

                lock (Adapter)
                {
                    Adapter.Fill(DBNameTable);
                }

                foreach (DataRow row in DBNameTable.Rows)
                {
                    DBNameList.Add(row["name"]);
                }

                return DBNameList;
            }
            catch (Exception e)
            {
                ArrayList NameList = new ArrayList();
                return NameList;
            }
        }

        private void  ModifyFile(string path, string newConString, string Fileindexof)
        {
            
          
            if (!File.Exists(path))
            {
                // 目录/文件不存在，建立目录/文件 
              //  MessageBox.Show(string.Format("'{0}'文件不存在", path));
                return;
            }
            //打开文件            
            //通过指定字符编码方式可以实现对汉字的支持，否则在用记事本打开查看会出现乱码 
            StreamReader m_streamReader = new StreamReader(path, System.Text.Encoding.GetEncoding("GB2312"));
            //使用StreamReader类来读取文件
            m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
            // 从数据流中读取每一行，直到文件的最后一行，并在richTextBox1中显示出内容           
            string save = "";
            string strLine = m_streamReader.ReadLine();
            while (strLine != null)
            {
                if (strLine.IndexOf(newConString) > 0)
                {
                    save += Fileindexof + "\r\n";
                }
                else
                {
                    save += strLine + "\r\n";
                }
                strLine = m_streamReader.ReadLine();
            }
            //关闭此StreamReader对象
            m_streamReader.Close();
            StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("UTF-8"));
            sw.Write(save);
            sw.Flush();
            sw.Close();
            
        }

        public void SetDirComboBox()
        {
           
            
        }

        public class FilePath
        {
            public string FIlepath { get; set; }
            public string newConString { get; set; }
            public string Fileindexof { get; set; }
        }
       
        private IPAddress[] GetIP()
        {
            string hostName = Dns.GetHostName();
            System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);            
          //  foreach (IPAddress ip in addressList)
         //   {               
           // }
           return addressList;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="num">1-7是配置wwwroot的配置文件，8-12是Service的配置文件</param>
        /// <param name="ip"></param>
        /// <param name="sqlname"></param>
        /// <param name="sqluid"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public FilePath GetPath(int num,string ip,string sqlname,string sqluid,string password,string appsqlname)
        {
            FilePath contex = new FilePath();
            switch (num)
            {
                case 1:
                    contex.FIlepath = @"D:\wwwroot\smop\web.config";                  
                    contex.Fileindexof = string.Format("<add name=\"Default\" connectionString=\"server = {0}; uid = {1}; pwd = {2};database={3};\" providerName=\"System.Data.SqlClient\" />", ip, sqluid, password,sqlname);
                    contex.newConString= "name=\"Default\"";
                    return contex;
                case 2:
                    contex.FIlepath = @"D:\wwwroot\smop\web.config";
                    contex.Fileindexof = string.Format("<add key=\"serverip\" value=\"{0}\" />", ip);
                    contex.newConString = "key=\"serverip\"";
                    return contex;
                case 3:
                    contex.FIlepath = @"D:\wwwroot\login\web.config";
                    contex.Fileindexof = string.Format("<add key=\"ConnectionString\" value=\"Data Source ={0}; Initial Catalog = {1}; User ID ={2}; Password = {3}; Connection Timeout = 15\"/>", ip, sqlname, sqluid, password);
                    contex.newConString = "key=\"ConnectionString\"";
                    return contex;
                case 4:
                    contex.FIlepath = @"D:\wwwroot\login\web.config";
                    contex.Fileindexof = string.Format(" <add baseAddress=\"http://{0}/EisDualService\"/>", ip);
                    contex.newConString = "baseAddress=";
                    return contex;
                case 5:
                    contex.FIlepath = @"D:\wwwroot\smopAppApi\web.config";
                    contex.Fileindexof = string.Format("<add name=\"SmopEntities\" connectionString=\"metadata = res://*/SmopModel.csdl|res://*/SmopModel.ssdl|res://*/SmopModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source={0};initial catalog={1};user id={2};password={3};MultipleActiveResultSets=True;App=EntityFramework&quot;\" providerName=\"System.Data.EntityClient\" />", ip, sqlname, sqluid, password);
                    contex.newConString = "name=\"SmopEntities\"";
                    return contex;
                case 6:
                    contex.FIlepath = @"D:\wwwroot\smopAppApi\web.config";
                    contex.Fileindexof = string.Format(" <add key=\"brokerIp\" value=\"{0}\" />", ip);
                    contex.newConString = "key=\"brokerIp\"";
                    return contex;
                case 7:
                    contex.FIlepath = @"D:\wwwroot\smopAppApi\web.config";
                    contex.Fileindexof = string.Format("  <add key=\"serverIp\" value=\"{0}\" />", ip);
                    contex.newConString = "key=\"serverIp\"";
                    return contex;
                case 8:
                    contex.FIlepath = @"D:\Services\Smop.Task.Schedule\Smop.Task.Schedule.exe.config";
                    contex.Fileindexof = string.Format("<add key=\"ConnectionStringSmop\" value=\"data source ={0}; initial catalog = {1}; user id = {2}; password = {3};\" />", ip, sqlname, sqluid, password);
                    contex.newConString = "key=\"ConnectionStringSmop\"";
                    return contex;

                case 9:
                    contex.FIlepath = @"D:\Services\Smop.Task.Schedule\Smop.Task.Schedule.exe.config";
                    contex.Fileindexof = string.Format("<add key=\"ConnectionString\" value=\"data source ={0}; initial catalog = {1}; user id = {2}; password = {3};\" />", ip,appsqlname,sqluid,password);
                    contex.newConString = "key=\"ConnectionString\"";
                    return contex;
                case 10:
                    contex.FIlepath = @"D:\Services\Smop.Task.Schedule\Smop.Task.Schedule.exe.config";
                    contex.Fileindexof = string.Format("<add key=\"AppWebApiDomain\" value=\"http://{0}:22742\" />", ip);
                    contex.newConString = "key=\"AppWebApiDomain\"";
                    return contex;
                case 11:
                    contex.FIlepath = @"D:\Services\Smop.Task.Schedule\Smop.Task.Schedule.exe.config";
                    contex.Fileindexof = string.Format("<add name=\"AppEntities\" connectionString=\"metadata = res://*/AppModel.csdl|res://*/AppModel.ssdl|res://*/AppModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source={0};initial catalog={1};user id={2};password={3};MultipleActiveResultSets=True;App=EntityFramework&quot;\" providerName=\"System.Data.EntityClient\" />", ip, appsqlname, sqluid, password);
                    contex.newConString = "name=\"AppEntities\"";
                    return contex;
                case 12:
                    contex.FIlepath = @"D:\Services\Smop.Task.Schedule\Smop.Task.Schedule.exe.config";
                    contex.Fileindexof = string.Format(" <add name=\"SmopEntities\" connectionString=\"metadata = res://*/SmopModel.csdl|res://*/SmopModel.ssdl|res://*/SmopModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source={0};initial catalog={1};user id={2};password={3};MultipleActiveResultSets=True;App=EntityFramework&quot;\" providerName=\"System.Data.EntityClient\" />", ip, sqlname, sqluid, password);
                    contex.newConString = "name=\"SmopEntities\"";
                    return contex;
                case 13:
                    contex.FIlepath = @"D:\SMOP\Client\ClientParamConfig.xml";
                    contex.Fileindexof = string.Format("<serverdualip key=\"serverdualip\" value=\"{0}\" />", ip);
                    contex.newConString = "key=\"serverdualip\"";
                    return contex;
                case 14:
                    contex.FIlepath = @"D:\SMOP\Client\ClientParamConfig.xml";
                    contex.Fileindexof = string.Format("<serverip key=\"serverip\" value=\"{0}\" />", ip);
                    contex.newConString = "key=\"serverip\"";
                    return contex;
                case 15:
                    contex.FIlepath = @"D:\SMOP\Client\ClientParamConfig.xml";
                    contex.Fileindexof = string.Format("<ConnectionString key=\"ConnectionString\" value=\"Data Source = {0}; Initial Catalog = {1}; Persist Security Info = True; User ID = {2}; Password = {3}; Connection Timeout = 15\" />", ip,sqlname,sqluid,password);
                    contex.newConString = "key=\"ConnectionString\"";
                    return contex;
                case 16:
                    contex.FIlepath = @"D:\SMOP\Server\ClientParamConfig.xml";
                    contex.Fileindexof = string.Format("<serverdualip key=\"serverdualip\" value=\"{0}\" />", ip);
                    contex.newConString = "key=\"serverdualip\"";
                    return contex;
                case 17:
                    contex.FIlepath = @"D:\SMOP\Server\ClientParamConfig.xml";
                    contex.Fileindexof = string.Format("<serverip key=\"serverip\" value=\"{0}\" />", ip);
                    contex.newConString = "key=\"serverip\"";
                    return contex;
                case 18:
                    contex.FIlepath = @"D:\SMOP\Server\ClientParamConfig.xml";
                    contex.Fileindexof = string.Format("<ConnectionString key=\"ConnectionString\" value=\"Data Source = {0}; Initial Catalog = {1}; Persist Security Info = True; User ID = {2}; Password = {3}; Connection Timeout = 15\" />", ip, sqlname, sqluid, password);
                    contex.newConString = "key=\"ConnectionString\"";
                    return contex;
                case 19:
                    contex.FIlepath = @"D:\SMOP\Server\Smop.ServerForm.exe.config";
                    contex.Fileindexof = string.Format("<add key=\"abp.syncuserurl\" value=\"http://{0}:8088/Account/Register4PrivateTask\" />", ip);
                    contex.newConString = "key=\"abp.syncuserurl\"";
                    return contex;
                case 20:
                    contex.FIlepath = @"D:\SMOP\Server\Smop.ServerForm.exe.config";
                    contex.Fileindexof = string.Format("<endpoint address=\"http://{0}:9011/EisDualService.svc\" binding=\"basicHttpBinding\" bindingConfiguration=\"basicHttpBinding_IEisDualService\" contract=\"Smop.Server.DualService.IEisDualService\" name=\"basicHttpBinding_IEisDualService\" />", ip);
                    contex.newConString = "bindingConfiguration=\"basicHttpBinding_IEisDualService\"";
                    return contex;
                case 21:
                    contex.FIlepath = @"D:\SMOP\Server\Smop.ServerForm.exe.config";
                    contex.Fileindexof = string.Format(" <endpoint address=\"http://{0}:9011/LoginService\" binding=\"basicHttpBinding\" bindingConfiguration=\"\" contract=\"Smop.Server.LoginServiceInterface.ILoginService\" name=\"LoginService\"></endpoint>", ip);
                    contex.newConString = "name=\"LoginService\"";
                    return contex;

                case 22:
                    contex.FIlepath = @"D:\wwwroot\kaifa\server\dist\appsettings.json";
                    contex.Fileindexof = string.Format("\"Default\": \"server={0};uid={1};pwd={2};database={3};MultipleActiveResultSets=True;Pooling=true;Max Pool Size=500;Min Pool Size=0\"",ip, sqluid, password, appsqlname);
                    contex.newConString = "Default";
                    return contex;
                case 23:
                    contex.FIlepath = @"D:\wwwroot\kaifa\server\dist\appsettings.json";
                    contex.Fileindexof = string.Format("\"ConnectionString\":\"{0}:6379,password=fJE3Iq5Mi58apVgHga6K\",", ip);
                    contex.newConString = "\"ConnectionString\"";
                    return contex;
                default:
                    return null;
            }
        }
        /// <summary>
        /// 修改文件只读
        /// </summary>
        /// <param name="aFilePath"></param>
        public void SetFileAttributes(string aFilePath)
        {
            if(!File.Exists(aFilePath)) return;
            if (File.GetAttributes(aFilePath).ToString().IndexOf("ReadOnly") != -1)
            {
                File.SetAttributes(aFilePath, FileAttributes.Normal);
            }
        }
    }
}